package org.chen.config;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * OkHttp客户端配置
 */
@Configuration
public class OkHttpConfig {

    @Value("${okhttp.connect-timeout:60}")
    private Integer connectTimeout;

    @Value("${okhttp.read-timeout:60}")
    private Integer readTimeout;

    @Value("${okhttp.write-timeout:60}")
    private Integer writeTimeout;

    @Value("${okhttp.max-idle-connections:5}")
    private Integer maxIdleConnections;

    @Value("${okhttp.keep-alive-duration:300}")
    private Integer keepAliveDuration;

    @Bean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                .readTimeout(readTimeout, TimeUnit.SECONDS)
                .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.SECONDS))
                .retryOnConnectionFailure(true)
                .build();
    }
}